package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.gprinter.io.PortParameters;
import com.gprinter.service.GpPrintService;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.BluetoothListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.ui.CustomListView;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Descriptions：打印机连接配置页面
 * <p>
 * Author：ChenME
 * Date：11/18/2016
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_port_configuration)
public class PortConfigurationActivity extends AppBaseActivity {

    @ViewById(R.id.lv_pairedDevices)
    CustomListView lv_pairedDevices;
    @ViewById(R.id.lv_newDevices)
    CustomListView lv_newDevices;
    @ViewById(R.id.btn_bluetoothScan)
    Button btn_bluetoothScan;

    public static final int REQUEST_ENABLE_BT = 2;//打开蓝牙

    private PortParameters mPortParam;//端口的参数
    private BluetoothAdapter bluetoothAdapter;//蓝牙适配器
    private BluetoothListAdapter mNewDevicesArrayAdapter;//新找到的蓝牙设备ListAdapter
    private List<Object> newDeviceList;
    private BluetoothListAdapter mPairedDevicesArrayAdapter;//已经配对的蓝牙设备的ListAdapter
    private List<Object> pariedDeviceList;

    /**
     * 扫描蓝牙的广播接收器
     */
    private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//蓝牙未配对
                    String bluetoothAddress = device.getAddress();
                    int newDeviceSize = newDeviceList.size();
                    int i = 0;
                    for (; i < newDeviceSize; i++) {
                        Object obj = newDeviceList.get(i);
                        if (obj instanceof BluetoothDevice) {
                            BluetoothDevice newBluetooth = (BluetoothDevice) obj;
                            if (bluetoothAddress.equals(newBluetooth.getAddress())) {
                                break;
                            }
                        }
                    }
                    if (i >= newDeviceSize) {
                        newDeviceList.add(device);
                    }
                    mNewDevicesArrayAdapter.notifyDataSetChanged();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setScanBtnEnabled(true);
                LogUtils.log("finish discovery" + mNewDevicesArrayAdapter.getCount());
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.string_portConfiguration_noneBluetoothDeviceFound).toString();
                    newDeviceList.add(noDevices);
                    mNewDevicesArrayAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    @AfterViews
    void onPageStart() {
        registerFindBluetoothBroadcast();
        initView();
        mPortParam = new PortParameters();
        mPortParam.setPortType(PortParameters.BLUETOOTH);
        getBluetoothDevice();
    }


    /**
     * 注册扫描蓝牙的广播接收器
     */
    private void registerFindBluetoothBroadcast() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mFindBlueToothReceiver, filter);
    }

    private void initView() {
        setDefaultTitle(this, R.string.string_portConfiguration_title);
        pariedDeviceList = new ArrayList<>();
        mPairedDevicesArrayAdapter = new BluetoothListAdapter(this, pariedDeviceList);
        lv_pairedDevices.setAdapter(mPairedDevicesArrayAdapter);
        lv_pairedDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectDevice((TextView) view, position, false);


            }
        });

        newDeviceList = new ArrayList<>();
        mNewDevicesArrayAdapter = new BluetoothListAdapter(this, newDeviceList);
        lv_newDevices.setAdapter(mNewDevicesArrayAdapter);
        lv_newDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectDevice((TextView) view, position, true);
            }
        });
    }

    private void selectDevice(TextView view, int position, boolean isNewDevice) {
        //如果正在扫描，则取消扫描
        cancelIfBluetoothIsDiscovering();

        String info = view.getText().toString();
        String noDevices = getResources().getText(R.string.string_portConfiguration_nonePaired).toString();
        String noNewDevice = getResources().getText(R.string.string_portConfiguration_noneBluetoothDeviceFound).toString();
        LogUtils.log(info);
        if (!info.equals(noDevices) && !info.equals(noNewDevice)) {

            Object obj = null;
            if (isNewDevice) {
                obj = newDeviceList.get(position);
            } else {
                obj = pariedDeviceList.get(position);

            }

            if (obj instanceof BluetoothDevice) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) obj;
                // Get the device MAC address, which is the last 17 chars in the View
//                    String address = info.substring(info.length() - 17);
                String address = bluetoothDevice.getAddress();
                mPortParam.setBluetoothAddr(address);
                connectBluetooth();
            }
        }
    }

    /**
     * 获取蓝牙设备
     */
    private void getBluetoothDevice() {
        //获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null) {
            App.toast("您的手机不支持蓝牙");
        } else {
            //蓝牙未打开
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                //蓝牙已经打开，开始获取设备
                getAndShowAllDevice();
            }
        }
    }

    /**
     * 获取并展示所有的蓝牙设备
     * 包括已配对的和可用的
     */
    private void getAndShowAllDevice() {
        getPairedBlueTooth();
        discoveryNewBlueBluetooth();
    }

    /**
     * 获取已配对的蓝牙
     */
    private void getPairedBlueTooth() {
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                pariedDeviceList.add(device);
            }
        } else {
            String noDevices = getResources().getText(R.string.string_portConfiguration_nonePaired).toString();
            pariedDeviceList.add(noDevices);
        }
        mPairedDevicesArrayAdapter.notifyDataSetChanged();
    }

    /**
     * 扫描可用设备
     */
    @Click(R.id.btn_bluetoothScan)
    void discoveryNewBlueBluetooth() {
        setScanBtnEnabled(false);
        newDeviceList.clear();
        mNewDevicesArrayAdapter.notifyDataSetChanged();
        cancelIfBluetoothIsDiscovering();
        bluetoothAdapter.startDiscovery();
    }

    /**
     * 如果蓝牙正在扫描，则取消扫描
     */
    private void cancelIfBluetoothIsDiscovering() {
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }

    private void setScanBtnEnabled(boolean enabled) {
        btn_bluetoothScan.setEnabled(enabled);
        btn_bluetoothScan.setText(enabled ? getString(R.string.string_portConfiguration_toSearchBtn)
                : getString(R.string.string_portConfiguration_searching));
    }

    /**
     * 跳转蓝牙列表的页面
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {//打开蓝牙返回的Result
            if (resultCode == Activity.RESULT_OK) {//蓝牙打开成功
                getAndShowAllDevice();
            } else {
                App.toast(R.string.string_portConfiguration_bluetoothIsNotEnabled);
            }
        }
    }

    /**
     * 开始连接蓝牙
     */
    public void connectBluetooth() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(GpPrintService.PORT_TYPE, mPortParam.getPortType());
        bundle.putString(GpPrintService.BLUETOOT_ADDR, mPortParam.getBluetoothAddr());
        intent.putExtras(bundle);
        this.setResult(Activity.RESULT_OK, intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        if (mFindBlueToothReceiver != null) {
            this.unregisterReceiver(mFindBlueToothReceiver);
        }
        cancelIfBluetoothIsDiscovering();
        super.onDestroy();
    }
}